﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mobile;
using System.Web.UI;
using System.Web.UI.WebControls;
using PaymentGateways;

namespace TranTekBE.ScanThuoc
{
    public partial class ScanThuoc1 : PageRequireLogin
    {
        dbScanThuocDataContext db = new dbScanThuocDataContext();
        public Database database = new Database(TinyLib.GetConfigKey("ConnectionString2"));
        string datecode = DateTime.Now.ToString("yyyyMMdd");
        //
        public ScanThuoc scanThuoc;
        //
        private int SoLanPhaiScan1Ca = 2;//số lần user phải scan trong 1 ca làm việc
        public tbl_LichLamViec LichLamViec;
        public LanScan lanScan;
        public int SoViTriPhaiScan = 0;
        public string PositionLogin;
        protected void Page_Load(object sender, EventArgs e)
        {
            LabelMessage.Text = "";
            PageInIt();
            if (!IsPostBack)
            {
                LoadData();
                LoadDdlVitri();
            }
        }

        void PageInIt()
        {
            this.Page.Form.DefaultButton = ButtonOK.UniqueID;
            TextBoxScan.Visible = true;
            ButtonOK.Visible = true;
            ButtonXong.Visible = true;
            ButtonScanThem.Visible = false;




            CheckStoreNameOfUserLogin();
            //get lich lam viec
            DateTime startDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            DateTime endDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
            var listLichLamViec = db.tbl_LichLamViecs.Where(c => c.CUA_HANG_DANG_LAM_VIEC == PositionLogin && c.ID_USER == UserInfo.UserID && c.NGAY_THEM_VAO >= startDate && c.NGAY_THEM_VAO <= endDate).ToList();
            SoViTriPhaiScan = listLichLamViec.Count * SoLanPhaiScan1Ca;
            CheckLanScan();
            //check lần scan
            if (SoViTriPhaiScan == 0)
            {//hom nay khong co lich
                LabelVitri.Text = "";
                LabelMessage.Text = "Hôm nay [" + UserInfo.UserName + "] không có lịch làm việc tại cửa hàng " + PositionLogin + ". Hãy kiểm tra lại lịch làm việc.";
                LabelMessage.ForeColor = Color.Red;
                TextBoxScan.Visible = false;
                ButtonOK.Visible = false;
                ButtonXong.Visible = false;
                return;
            }

        }

        public void CheckStoreNameOfUserLogin()
        {
            string ip = HttpContext.Current.Request.UserHostAddress;
            if (ip == "::1" || ip.StartsWith("192.168.1."))
            {
                ip = "PHARMACITYHBT";
            }
            string sql = @"SELECT [C007001] Name 
                      ,[C007002] Ip
                      FROM [192.168.1.98\CAMSOFT].[POSPRO_20130107].[dbo].[T0070]
                      WHERE C007001 NOT IN ('RACHMIEU','PMT')";


            var ds = database.ExecuteQuery(sql);
            if (ds.Tables.Count > 0)
            {
                var dt = ds.Tables[0];
                var list = dt.AsEnumerable().Select(c => new
                {
                    Name = c.Field<string>("Name"),
                    Ip = c.Field<string>("Ip")
                }).ToList();
                var firstOrDefault = list.FirstOrDefault(c => c.Ip == ip);
                {
                    if (firstOrDefault != null)
                        PositionLogin = firstOrDefault.Name;
                    return;
                }
            }

            Response.Write("Không tìm thấy vị trí đăng nhập của bạn. Vui lòng liên hệ Admin");
            Response.End();
        }

        public void CheckLanScan()
        {
            lanScan = db.LanScans.FirstOrDefault(c => c.StoreName == PositionLogin && !c.IsFinish);
            if (lanScan == null)
            {//them mot lan scan moi
                lanScan = new LanScan()
                {
                    CreatedDate = DateTime.Now,
                    Lan = db.LanScans.Count() + 1,
                    StoreName = PositionLogin
                };
                db.LanScans.InsertOnSubmit(lanScan);
                db.SubmitChanges();
            }
        }

        private void LoadData()
        {
            if (SoViTriPhaiScan == 0)
            {//hom nay khong co lich
                return;
            }
            //lấy lần scan thuoc hiện tại cua user
            var lst = db.ScanThuocs.Where(c => c.DateCode == datecode && c.UserId == UserInfo.UserID).ToList();
            if (lst.Count(c => c.IsFinish) >= SoViTriPhaiScan)
            {//xong
                LabelMessage.Text = "Hôm nay " + UserInfo.UserName + " đã Scan xong " + SoViTriPhaiScan + " vị trí " + string.Join(", ", lanScan.ScanThuocs.Where(c => c.UserId == UserInfo.UserID).Select(c => c.VitriScan).ToArray());
                LabelMessage.ForeColor = Color.Blue;
                LabelVitri.Text = "";
                TextBoxScan.Visible = false;
                ButtonOK.Visible = false;
                ButtonXong.Visible = false;
                return;
            }
            //----
            if (lst.Count == 0)
            {//chua lam cai nao het
                //them moi
                var vt = GetViTriChuaScan();
                scanThuoc = new ScanThuoc()
                {
                    DateCode = datecode,
                    IsFinish = false,
                    CreatedDate = DateTime.Now,
                    UserId = UserInfo.UserID,
                    VitriScan = vt.ViTri,
                    LanScanId = lanScan.LanScanId,
                };
                db.ScanThuocs.InsertOnSubmit(scanThuoc);
                db.SubmitChanges();

            }

            else//dang lam lỡ dỡ
            {
                scanThuoc = db.ScanThuocs.FirstOrDefault(c => !c.IsFinish);
                if (scanThuoc == null)
                {//them moi
                    var vt = GetViTriChuaScan();
                    scanThuoc = new ScanThuoc()
                    {
                        DateCode = datecode,
                        IsFinish = false,
                        CreatedDate = DateTime.Now,
                        UserId = UserInfo.UserID,
                        VitriScan = vt.ViTri,
                        LanScanId = lanScan.LanScanId,
                    };
                    db.ScanThuocs.InsertOnSubmit(scanThuoc);
                    db.SubmitChanges();
                }
            }
            // show vitri
            LabelVitri.Text = scanThuoc.VitriScan;
            hfScanThuocId.Value = scanThuoc.ScanThuocId.ToString();
            hfLanScanId.Value = lanScan.LanScanId.ToString();
        }

        private void LoadDdlVitri()
        {
            var model = db.ScanThuocs.Where(c => c.LanScanId == lanScan.LanScanId && c.DateCode == datecode && c.UserId == UserInfo.UserID).ToList(); //lanScan.ScanThuocs.ToList();
            if (model.Count > 0)
            {
                ddlVitri.DataSource = model;
                ddlVitri.DataValueField = "ScanThuocId";
                ddlVitri.DataTextField = "ViTriScan";
                ddlVitri.DataBind();
                LoadGridView2();
            }
        }

        private void LoadGridView2()
        {
            int id = int.Parse(ddlVitri.SelectedValue);
            var model = db.ScanThuocs.FirstOrDefault(c => c.ScanThuocId == id);
            if (model != null)
            {
                if (model.IsFinish)
                {
                    ButtonScanThem.Visible = true;
                    ButtonScanThem.Text = "Scan Thêm Vào " + model.VitriScan;

                }
                else
                {
                    ButtonScanThem.Visible = false;

                }
                GridView2.DataSource = db.ChiTietScans.Where(c => c.ScanThuocId == id).ToList();
                GridView2.DataBind();
            }


        }

        protected void ButtonOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TextBoxScan.Text.Trim()))
            {
                GridView1.Columns.Clear();
                return;
            }
            if (SoViTriPhaiScan == 0) return;
            var list = TextBoxScan.Text.Split(';').ToList();
            if (list.Count > 1)//check theo ma~ thuoc
            {
                #region check theo ma thuoc
                int scanthuocId = int.Parse(hfScanThuocId.Value);
                var model = db.GetProductById(PositionLogin, list[0].Trim()).ToList();
                if (model.Count > 0)//
                {
                    if (!db.ChiTietScans.Any(c => c.ScanThuocId == scanthuocId && c.ThuocId == model[0].ProductId))
                    {
                        //
                        db.ChiTietScans.InsertOnSubmit(new ChiTietScan()
                        {
                            CreatedDate = DateTime.Now,
                            ScanThuocId = scanthuocId,
                            TenThuoc = model[0].ProductName,
                            ThuocId = model[0].ProductId,
                            ViTriCu = model[0].Vitri1,
                            ViTriMoi = LabelVitri.Text
                        });
                        db.SubmitChanges();
                        LabelMessage.Text = "Thành công";
                        LabelMessage.ForeColor = Color.Green;
                    }
                    else
                    {
                        LabelMessage.Text = "Loại thuốc bạn này đã scan rồi.";
                        LabelMessage.ForeColor = Color.Tan;
                    }
                    GridView1.DataSource = model;
                    GridView1.DataBind();

                }
                else
                {
                    LabelMessage.Text = "Không tìm thấy kết quả";
                    LabelMessage.ForeColor = Color.Red;
                }
                #endregion check theo ma thuoc
            }
            else//theck theo ma vach
            {
                #region check theo ma vạch
                int scanthuocId = int.Parse(hfScanThuocId.Value);
                var model = db.GetProductByMaVach(PositionLogin, TextBoxScan.Text.Trim()).ToList();
                if (model.Count > 0)//
                {
                    if (!db.ChiTietScans.Any(c => c.ScanThuocId == scanthuocId && c.ThuocId == model[0].ProductId))
                    {
                        //
                        db.ChiTietScans.InsertOnSubmit(new ChiTietScan()
                        {
                            CreatedDate = DateTime.Now,
                            ScanThuocId = scanthuocId,
                            TenThuoc = model[0].ProductName,
                            ThuocId = model[0].ProductId,
                            ViTriCu = model[0].Vitri1,
                            ViTriMoi = LabelVitri.Text
                        });
                        db.SubmitChanges();
                        LabelMessage.Text = "Thành công";
                        LabelMessage.ForeColor = Color.Green;
                    }
                    else
                    {
                        LabelMessage.Text = "Loại thuốc bạn này đã scan rồi.";
                        LabelMessage.ForeColor = Color.Tan;
                    }
                    GridView1.DataSource = model;
                    GridView1.DataBind();

                }
                else
                {
                    LabelMessage.Text = "Không tìm thấy mã vạch này";
                    LabelMessage.ForeColor = Color.Red;
                }
                #endregion check theo ma vạch
            }
            TextBoxScan.Text = "";
            TextBoxScan.Focus();
            LoadGridView2();
        }

        protected void ButtonXong_Click(object sender, EventArgs e)
        {
            int scanthuocid = int.Parse(hfScanThuocId.Value);
            var a = db.ScanThuocs.FirstOrDefault(c => c.ScanThuocId == scanthuocid);
            a.IsFinish = true;
            db.SubmitChanges();
            Response.Redirect(Request.RawUrl);
        }

        protected void ddlVitri_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadGridView2();
        }

        vViTriChuaScan GetViTriChuaScan()
        {
            var vt = db.vViTriChuaScans.Where(c => c.CuaHang == PositionLogin).OrderBy(c => c.Chu).ThenBy(c => c.So).FirstOrDefault();
            if (vt == null)
            {
                lanScan = db.LanScans.FirstOrDefault(c => !c.IsFinish);
                lanScan.IsFinish = true;
                db.SubmitChanges();
                Response.Redirect(Request.RawUrl);
            }
            return vt;
        }

        protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView2.PageIndex = e.NewPageIndex;
            LoadGridView2();
        }

        protected void ButtonScanThem_Click(object sender, EventArgs e)
        {
            try
            {
                int id = int.Parse(ddlVitri.SelectedValue);
                var model = db.ScanThuocs.FirstOrDefault(c => c.ScanThuocId == id);
                model.IsFinish = false;
                db.SubmitChanges();
                Response.Redirect(Request.RawUrl);
            }
            catch
            {
            }
        }
    }
}